package com.kermitye.treenodelib

import java.util.*

/**
 * 树节点
 */
data class TreeNode<T>(
    // 数据
    var value: T,
    /*父节点*/
    var parent: TreeNode<T>? = null,
    /*是否展开*/
    var isExpand: Boolean = false,
    /*是否选中*/
    var isSelect: Boolean = false,
    /*子节点*/
    var children: MutableList<TreeNode<T>>? = null
) {

    /**
     * 设置子类集合
     */
    fun setChildList(childList: MutableList<TreeNode<T>>) {
        children = childList.apply {
            forEach {
                it.parent = this@TreeNode
            }
        }
    }

    /**
     * 添加子节点
     */
    fun addChild(child: TreeNode<T>?) {
        if (child == null) return
        if (children == null) children = ArrayList()
        children?.add(child)
        child.parent = this
    }

    /**
     * 获取层级
     */
    fun getLevel(): Int {
        return if (parent == null) 0 else parent!!.getLevel() + 1
    }

    /**
     * 是否存在上级
     */
    fun hasParent(): Boolean = parent != null

    /**
     * 是否存在下级
     */
    fun hasChild():Boolean = !children.isNullOrEmpty()

}